package cn.eastseven.netclient;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SocketClient {

	private static final Logger log = LoggerFactory.getLogger(SocketClient.class);
	
	public static void main(String[] args) throws Exception {
		log.debug("java socket client");
		
		SocketChannel socketChannel = SocketChannel.open();
		socketChannel.configureBlocking(false);
		
		if(!socketChannel.connect(new InetSocketAddress("127.0.0.1", 12345))) {
			while(!socketChannel.finishConnect()) {
				log.debug("....");
			}
		}
		
		socketChannel.write(ByteBuffer.wrap("hello , i am java nio socket from client \r\n".getBytes()));
		socketChannel.write(ByteBuffer.wrap("q\r\n".getBytes()));
		
		while(true) {
			ByteBuffer dst = ByteBuffer.allocate(1024);
			int read = socketChannel.read(dst);
			if(read > 0) {
				dst.flip();
				log.debug("由服务器端接收到的响应数据：" + new String(dst.array(), 0, read));
				socketChannel.close();
				break;
			}
		}
		log.debug("通讯完毕");
	}

}
